package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
//import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;

import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    /**
     * app登录
     */
    @Override
    public ResponseResult loginAuth(LoginDto loginDto) {
        log.info("app登录:{}",loginDto);
        // isBlank 空值 空串 空格 isEmpty 空值 空串
        // 判断入参是否为空
        if (StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())) {
            String phone = loginDto.getPhone();
            String pwd = loginDto.getPassword();
            // 根据手机号查询用户信息是否存在
            ApUser one = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            // 存在就验证密码
            boolean checkpw = BCrypt.checkpw(pwd, one.getPassword());
            if (!checkpw) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 登录成功就根据用户id生成token并响应
            String token = AppJwtUtil.getToken(one.getId().longValue());
            one.setPassword("");
            Map resultMap = new HashMap();
            resultMap.put("token", token);
            resultMap.put("user", one);

            return ResponseResult.okResult(resultMap);
        } else {
            // 用户名和密码都为空 游客登录逻辑
            Map resultMap = new HashMap();
            String token = AppJwtUtil.getToken(0L);
            resultMap.put("token", token);
            return ResponseResult.okResult(resultMap);
        }
    }

}
